var rMenu;//树的右键菜单
var zTree;
var gNode;
var setting = {
    async : {
        enable : true,
        url : "/do/menu/getAll",
        dataType:"json",
        dataFilter : filter
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pid",
        },
        key: {
            // name: "text"
        }
    },
    callback : {
        onRightClick : OnRightClick,
        onAsyncSuccess: zTreeOnAsyncSuccess
    }
};

function zTreeOnAsyncSuccess(event, treeId, msg) {
    //异步加载完后展开到第二级节点
    var nodes = zTree.getNodes();
    for (var i = 0; i < nodes.length; i++) { //设置节点展开
        zTree.expandNode(nodes[i], true, false, true);

    }
}

function filter(treeId, parentNode, childNodes) {
    if (!childNodes)
        return null;
    for (var i = 0, l = childNodes.length; i < l; i++) {
        childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
    }
    return childNodes;
}
//初始化
$(document).ready(function() {
    $.fn.zTree.init($("#tree"), setting);
    zTree = $.fn.zTree.getZTreeObj("tree");


    rMenu = $("#rMenu");
    hideRMenu();

    $("#add").bind("click",btnAddChildNodes);
    $("#delete").bind("click",btnDeleChildNodes);
    $("#modify").bind("click",btnModifyNode);

    $('#myModal').on('hidden.bs.modal', modalHiddenEvent);//模态框隐藏触发
    $("#m_btn").bind("click",saveOrUpdateNode);
});

//ztree 右键方法
function OnRightClick(event, treeId, treeNode) {
    if (!treeNode && event.target.tagName.toLowerCase() != "button"
        && $(event.target).parents("a").length == 0) {
        zTree.cancelSelectedNode();
        gNode=null;
        showRMenu("root", event.clientX, event.clientY);
    } else if (treeNode && !treeNode.noR) {
        zTree.selectNode(treeNode);
        gNode=treeNode;
        showRMenu("node", event.clientX, event.clientY);
    }
}

//展示右键菜单
function showRMenu(type, x, y) {
    $("#rMenu ul").show();
    if (type == "root") {
        $("#modify").hide();
        $("#delete").hide();
    } else {
        $("#modify").show();
        $("#delete").show();
    }
    rMenu.css({
        "top" : y + "px",
        "left" : x + "px",
        "visibility" : "visible"
    });

    $("body").bind("mousedown", onBodyMouseDown);
}

//隐藏右键菜单
function hideRMenu() {
    if (rMenu)
        rMenu.css({
            "visibility" : "hidden"
        });
    $("body").unbind("mousedown", onBodyMouseDown);
}
function onBodyMouseDown(event) {
    if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
        rMenu.css({
            "visibility" : "hidden"
        });
    }
}

var rMenuBtnType=0;
/**
 * 点击添加下级
 */
function btnAddChildNodes(){
    hideRMenu();
    rMenuBtnType=1;
    $('#myModal').modal('show');
    if(gNode && gNode!=null){
        $('#myModalLabel').html(gNode.name+"-添加下级");
    }else{
        $('#myModalLabel').html("添加下级");
    }
}

function btnModifyNode(){
    hideRMenu();
    rMenuBtnType=2;
    $('#myModal').modal('show');
    if(gNode && gNode!=null){
        findById(gNode.id)
    }
}

function findById(id) {
    $.ajax({
        type: 'get',
        url: '/do/menu/'+id,
        dataType:"json",
        success: function (data) {
            if(data.code==1){
                var node = data.data;
                $("#menuName").val(gNode.name);
                $("#menuUrl").val(node.url);
                $("#menuIcon").val(node.icon);
                $("#menuOrder").val(node.order);
                $('#myModalLabel').html(gNode.name+"-编辑");
            }else{
                alert(data.msg)
            }
        }
    });
}

/**
 * 点击删除
 */
function btnDeleChildNodes(){
    hideRMenu();
    if(gNode.children && gNode.children.length>0){
        alert("该菜单有下级，无法删除");
        return ;
    }
    $.ajax({
        type: 'delete',
        url: '/do/menu/'+gNode.id,
        dataType:"json",
        success: function (data) {
            if(data.code==1){
                //移除页面上的节点
                zTree.removeNode(gNode);
            }else{
                alert(data.msg)
            }
        },
        complete: function () {
        }
    });
}

/**
 * 模态框隐藏后 清空form表单数据
 */
function modalHiddenEvent(){
    gNode=null;
    $('#errorMsg').html("");
    $('#menuForm')[0].reset();
    rMenuBtnType==0;
}

function saveOrUpdateNode(){

    var pid="",id="",name="",canParent=0;
    if(rMenuBtnType==1){//添加下级
        if( gNode!=null){
            pid=gNode.id;
        }

    }else if(rMenuBtnType==2){
        pid=gNode.pid;
        id=gNode.id;
        if(gNode.isParent) {canParent=1;}
    }else{
        return ;
    }
    name=$("#menuName").val();
    var menuUrl = $("#menuUrl").val();
    var icon = $("#menuIcon").val();
    var order = $("#menuOrder").val();
    if(name == "" || name==null){
        return ;
    }
    if(order == "" || order==null){
        order=1 ;
    }
    $("#m_btn").attr('disabled',"true");
    $.ajax({
        type: 'post',
        url: '/do/menu/edit',
        data: {
            id:id,
            pid:pid,
            text:name,
            url:menuUrl,
            icon:icon,
            order:order
        },
        dataType:"json",
        success: function (data) {
            $('#m_btn').removeAttr("disabled");
            if(data.code==1){
                $('#myModal').modal('toggle');
                //重新初始化树，为了排序生效
                $.fn.zTree.init($("#tree"), setting);
            }else{
                $('#errorMsg').html(data.msg);
                //2秒后隐藏
                $('#errorMsg').delay(2000).queue(function(){$(this).html("");})

            }
        },

        complete: function () {
        }
    });
}


